package com.culture.config.common.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

/**
* FreemarkerUtil
* @author LongWuwei
* @version 1.0
*/
@Slf4j
public class FreemarkerUtil {
	
	private FreemarkerUtil() {
		throw new IllegalStateException("FreemarkerUtil class");
	}
	
	/**
	* build Template
	*
	* @param templateFileName
	* @param paramMap
	* @return
	*/
	public static String buildTemplate(String templateFileName, Object paramMap) {		
		return buildTemplateContent(readTemplateFromResource(templateFileName),paramMap);
	}		

	/**
	* buildTemplateContent from string
	*
	* @param templateContent
	* @param paramMap
	* @return
	*/
	public static String buildTemplateContent(String templateContent, Object params) {
		String templateName = "templateContent";
		if (StringUtils.isBlank(templateContent)) {
			log.warn("getTemplateContent is emtpy");
			return templateContent;
		}
		if(Objects.isNull(params)){
			params = new HashMap<String, Object>();
		}
		try {
			Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
			StringTemplateLoader stringLoader = new StringTemplateLoader();
			stringLoader.putTemplate(templateName, templateContent);
			cfg.setTemplateLoader(stringLoader);
			Template template = cfg.getTemplate(templateName, "UTF-8");
			Writer out = new StringWriter(2048);
			template.process(params, out);
			String text = out.toString();
			out.flush();		
			return text;
		}catch(Exception ex) {
			log.error("getTemplateContent exception:{}",ex);
		}
		return null;
	}

	/**
	 * readTemplateDataFromResource
	 * @param templateFilePath
	 * @return TemplateFileData
	 */
	private static String readTemplateFromResource(String resourceFilePath) {
		String fileContent= null;
		log.info("rsFileName:" + resourceFilePath);
		try {
			ClassPathResource classPathResource = new ClassPathResource(resourceFilePath);
			if(!classPathResource.exists()) {
				log.warn("no resource for:{}",resourceFilePath);
				return fileContent;
			}
			InputStream ins = classPathResource.getInputStream();		
			ByteArrayOutputStream result = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int length;
			while ((length = ins.read(buffer)) != -1) {
				result.write(buffer, 0, length);
			}
			fileContent = result.toString("UTF-8");
			result.close();
			ins.close();
		}catch(Exception ex) {
			log.error("readTemplateFromResource exception:{}",ex);
		}
		
		return fileContent;
	}
}
